package com.mikiya.plugin;

import com.mikiya.plugin.dto.DataFetchDTO;
import com.mikiya.plugin.dto.DataFetchItemDTO;
import com.mikiya.plugin.dto.DataFetchReqDTO;
import com.mikiya.plugin.util.HttpUtil;
import com.mikiya.plugin.util.JsonUtil;
import okhttp3.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class DataFetch {
    private static final String URL = "https://dev.usemock.com/65825b2d79978bf80f70e939/recycle";

    public static Map<String, Integer> get(String domain) {
        DataFetchReqDTO request = new DataFetchReqDTO(domain);

        Map<String, Integer> map = new HashMap<>();
        Response response = HttpUtil.post(URL, JsonUtil.toString(request));
        if (response == null || !response.isSuccessful() || response.body() == null) {
            return map;
        }
        String data = null;
        try {
            data = response.body().string();
        } catch (IOException e) {
        }
        if (data == null || data.length() == 0) {
            return map;
        }

        DataFetchDTO fetchDTO = JsonUtil.toObject(data, DataFetchDTO.class);
        if (fetchDTO == null || Objects.isNull(fetchDTO.getData())) {
            return map;
        }
        for (DataFetchItemDTO item : fetchDTO.getData()) {
            map.put(item.getPath(), item.getUsedCount());
        }
        return map;
    }

}
